#include "../config.h"

#include <glibmm/i18n.h>

#include "options.h"

namespace gpyp {

bool MainOptionGroup::on_post_parse(Glib::OptionContext &context, Glib::OptionGroup &group) {
  if (config_dir_ && config_dir_[0]) {
    config_dir_s_ = Glib::filename_to_utf8(config_dir_);
  }
  return Glib::OptionGroup::on_post_parse(context, group);
}

MainOptionGroup::MainOptionGroup() :
  Glib::OptionGroup("Main Group", "Main Options"),
  use_config_      (TRUE),
  config_dir_      (NULL),
  max_logs_        (10)
{
  /* g_get_user_config_dir内でg_strdupした結果をglib内で保持してて開放しない仕様らしい。 */
  {
    const gchar *config_dir = g_get_user_config_dir();
    if (!config_dir || !config_dir[0]) config_dir = g_get_home_dir();
    gchar *p = g_build_filename(config_dir, "gpyp3", NULL);
    gchar *e = g_filename_to_utf8(p, -1, NULL, NULL, NULL);
    config_dir_s_ = e;
    g_free(e);
    g_free(p);
  }

  /* dapperのgtkmmだとオプションを指定しなくても何故か値が上書きされるのでCで書く */
  memset(entries_, 0, sizeof(entries_));

  entries_[0].long_name       = "disable-config";
  entries_[0].flags           = G_OPTION_FLAG_IN_MAIN | G_OPTION_FLAG_REVERSE;
  entries_[0].arg             = G_OPTION_ARG_NONE;
  entries_[0].arg_data        = &use_config_;
  entries_[0].description     = _("Do not load or save configuration file");

  entries_[1].long_name       = "config-dir";
  entries_[1].short_name      = 'c';
  entries_[1].flags           = G_OPTION_FLAG_IN_MAIN | G_OPTION_FLAG_FILENAME;
  entries_[1].arg             = G_OPTION_ARG_FILENAME;
  entries_[1].arg_data        = &config_dir_;
  entries_[1].description     = _("Path to configuration files directory");
  entries_[1].arg_description = "PATH";

  entries_[2].long_name       = "max-logs";
  entries_[2].flags           = G_OPTION_FLAG_IN_MAIN;
  entries_[2].arg             = G_OPTION_ARG_INT;
  entries_[2].arg_data        = &max_logs_;
  entries_[2].description     = _("Maximum number of log files");
  entries_[2].arg_description = "NUM";

  g_option_group_add_entries(gobj(), entries_);
}
MainOptionGroup::~MainOptionGroup() {
  if (config_dir_) g_free(config_dir_);
}

//========================
// OptionContext
bool OptionContext::get_use_config() const {
  return main_.use_config_;
}
const Glib::ustring &OptionContext::get_config_dir() const {
  return main_.config_dir_s_;
}
int OptionContext::get_max_logs() const {
  return main_.max_logs_;
}

OptionContext::OptionContext() {
  set_main_group(main_);
  set_help_enabled(true);
  set_ignore_unknown_options(true);
}

}/* namespace gpyp */
